"""
Python cook book ch 8.3
"""
from socket import socket, AF_INET, SOCK_STREAM
from PyCmpltrtok.common import sep


class LazyConn(object):

    def __init__(self, addr, family=AF_INET, type=SOCK_STREAM):
        self.addr = addr
        self.family = family
        self.type = type
        self.sock = None

    def __enter__(self):
        if self.sock is not None:
            raise RuntimeError('Already connected!')
        self.sock = socket(self.family, self.type)
        sep(f'Connecting to {self.addr}')
        self.sock.connect(self.addr)
        sep(f'Connected')
        return self.sock

    def __exit__(self, exc_type, exc_val, exc_tb):
        sep(f'Closing ...')
        self.sock.close()
        self.sock = None
        sep('Closed')


if '__main__' == __name__:
    from functools import partial

    # HOST = 'www.rateok.site'
    # HOST = 'www.google.com'
    HOST = 'www.baidu.com'
    conn = LazyConn((HOST, 80))
    with conn as s:
        s.send(b'GET / HTTP/1.1\r\n')
        s.send(f'Host: {HOST}\r\n'.encode(encoding='utf8'))
        s.send(b'\r\n')
        # resp = b''.join(iter(partial(s.recv, 4096), b''))
        resp = s.recv(4096)
    sep('response')
    print(resp.decode(encoding='utf8'))
    sep('All over')
